<template>
	<view class="shop">
		<view class="biao">
			<view class="cu-form-group ">
				<view class="title">店铺名称：</view>
				<view class="title" style="flex-grow: 1;">{{content.shopName}}</view>
			</view>
			<view class="cu-form-group ">
				<view class="title">店铺地址：</view>
				<view class="title" style="flex-grow: 1;">{{content.shopAddress}}</view>
			</view>
			<view class="cu-form-group" @click="biaozu">
				<view class="title">标注位置：</view>
				<input :placeholder="address || '点击选择位置'" name="input" disabled></input>
				<text v-if="!address" class='cuIcon-locationfill text-orange'></text>
			</view>
			<view class="cu-form-group ">
				<view class="title">店铺电话：</view>
				<input placeholder="请输入" name="input" v-model="list.shopPhone"></input>
			</view>
			<view class="biao_05 cu-form-group">
				<view class="title">营业时间：</view>
				<view class="time" >
					<view class="biao_05_2"> 
						<view class="uni-list-cell-db">
							<picker mode="time" :value="time"  @change="bindTimeChange" style="margin-top: 6px;">
								<view class="uni-input">{{time}}</view>
							</picker>
						</view>
					</view>
					<view class="biao_05_2" style="margin: 10upx 10px 0 0;">--</view>
					<view class="uni-list-cell-db">
						<picker mode="time" :value="time_close"  @change="bindTimeChange_close" style="margin-top: 6px;">
							<view class="uni-input">{{time_close}}</view>
						</picker>
					</view>
				</view>
			</view>
			<view class="cu-form-group ">
				<view class="title">购买须知：</view>
			</view>
			<view class="cu-form-group">
				<textarea maxlength="-1" :disabled="modalName!=null" @input="textareaAInput" placeholder="请输入购买须知" v-model="list.notice"></textarea>
			</view>
			<view class="cu-form-group ">
				<view class="title">是否营业：</view>
				<view class="title" >
					<switch @change="switchChange" :checked="switchA" color="#e54d42"></switch> 
				</view>
			</view>
		</view>
		<view style="height: 80px;"></view>
		<view class="p_btn">
			<view class=" flex flex-direction">
				<button @click="sub()" class="cu-btn bg-red margin-tb-sm lg">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import uniIcon from "@/components/uni-icon/uni-icon.vue"
	import wPicker from "@/components/w-picker/w-picker.vue";
	export default {
		data() {
			return {
				content: {}, // 店铺基本信息（不可编辑部分）
				list: { // 可编辑表单数据
					shopPhone: '',
					notice: '',
					location: null,
					isOpen: 1
				},
				address: '',
				time: '09:00',
				time_close: '19:00',
				switchA: true, // 是否营业开关状态
				modalName: null
			};
		},
		onLoad() {
			this.getShopDetail()
		},
		components: {
			uniIcon,
			wPicker
		},
		methods: {
			// 获取店铺详情
			async getShopDetail() {
				try {
					const res = await this.$api.http.getShopInfo()
					if (res.status === 1) {
						this.content = res.data
						// 初始化表单数据
						this.list.shopPhone = res.data.shopPhone || ''
						this.list.notice = res.data.notice || ''
						this.list.location = res.data.location || null
						this.list.isOpen = res.data.isOpen || 1
						this.switchA = res.data.isOpen === 1
						
						// 初始化时间
						this.time = res.data.businessHoursStart || '09:00'
						this.time_close = res.data.businessHoursEnd || '19:00'
						
						// 初始化地址
						if (res.data.location) {
							this.address = res.data.location.address
						}
					}
				} catch (err) {
					console.error('获取店铺信息失败:', err)
				}
			},
			
			bindTimeChange: function(e) {
				this.time = e.target.value
			},
			bindTimeChange_close: function(e) {
				this.time_close = e.target.value
			},
			
			// 营业状态切换
			switchChange(e) {
				this.switchA = e.detail.value
				this.list.isOpen = e.detail.value ? 1 : 0
			},
			
			// 文本域输入
			textareaAInput(e) {
				this.list.notice = e.detail.value
			},
			
			//选择位置
			biaozu() {
				const that = this

				//#ifdef MP-WEIXIN 
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							uni.authorize({
								scope: 'scope.userLocation',
								success() {
									that.chooseLocation()
									return;
								}
							})
						} else {
							that.chooseLocation()
							return;
						}
					}
				})
				//#endif

				//#ifndef MP-WEIXIN 
				that.chooseLocation()
				//#endif
			},
			
			chooseLocation() {
				const that = this
				uni.chooseLocation({
					success: function(res) { 
						that.address = res.name
						that.list.location = {
							latitude: res.latitude,
							longitude: res.longitude,
							address: res.address
						}
					}
				});
			},
			
			// 提交表单
			async sub() {
				// 表单验证
				// 修复：优化手机号验证正则
				  // 1. 先去除可能的空格等干扰字符
				  const phone = this.list.shopPhone.replace(/\s/g, '');
				  // 2. 使用更完善的正则（支持13-19开头的所有号段）
				  const phoneReg = /^1[3-9]\d{9}$/;
				  
				  if (!phoneReg.test(phone)) {
				    return uni.showToast({ title: '请输入正确的11位手机号', icon: 'none' })
				  }
				// 新增营业时间合法性验证
				  const start = this.time; // 格式为"HH:MM"
				  const end = this.time_close;
				  
				  // 将时间转换为分钟数进行比较
				  const [startHour, startMinute] = start.split(':').map(Number);
				  const [endHour, endMinute] = end.split(':').map(Number);
				  
				  const startTime = startHour * 60 + startMinute;
				  const endTime = endHour * 60 + endMinute;
				  
				  if (endTime <= startTime) {
				    return uni.showToast({ 
				      title: '结束时间必须晚于开始时间', 
				      icon: 'none' 
				    });
				  }
				if (!this.list.shopPhone) {
					return uni.showToast({ title: '请输入店铺电话', icon: 'none' })
				}
				
				if (!this.list.location) {
					return uni.showToast({ title: '请标注店铺位置', icon: 'none' })
				}
				
				try {
					// 构建提交参数
					const params = {
						shopId: this.content.shopId,
						shopPhone: this.list.shopPhone,
						businessHoursStart: this.time,
						businessHoursEnd: this.time_close,
						notice: this.list.notice,
						isOpen: this.list.isOpen,
						location: this.list.location
					}
					
					// 调用保存接口
					await this.$api.http.saveShopEdit(params)
					
					    // 提交成功提示（使用全局msg函数）
					    this.$api.msg('保存成功');
					    // 延迟返回，确保用户看到提示
					    setTimeout(() => {
					      uni.navigateBack()
					    }, 1500);
					// 返回上一页
					uni.navigateBack()
				} catch (err) {
					console.error('保存店铺信息失败:', err)
			  }
			}
		}
	}
</script>

<style lang="less">
	/* 保持原有样式不变 */
	.shop {background-color: #fff;min-height: 100vh;
		 .uni-input {background-color: #fff;} 
		.biao span {
			color: #F6996D;
			padding-right: 5px;
		}

		.biao_01 {
			padding: 20px 10px;
			border-bottom: 1px solid #EDEDED;
			display: flex;font-size: 15px;
		}

		.biao_01_l {
			padding-top: 5px;
		}

		.biao_02 {
			padding: 5px 10px;
			border-bottom: 1px solid #EDEDED;
			display: flex;
			justify-content: space-between;
		}

		.biao_02_l {
			padding-top: 10px;
		}

		.biao_03 {
			padding: 13px 10px 10px;
			border-bottom: 1px solid #EDEDED;
			display: flex;
		}

		.jgkc {
			padding: 10px;
			background-color: #F2F2F2;
		}

		.pro_btn {
			background-color: #E5E5E5;
			padding: 10px;
			text-align: center;
			margin: 10px;
			border-radius: 20px;
			background-color: #DF421D;
			color: #fff;
			position: fixed;
			bottom: 0;
			z-index: 99;
			width: 89%;
		}

		.biao_04 {
			padding: 20px 10px;
			border-bottom: 1px solid #EDEDED;
			display: flex;
		}

		.biao_04_l {
			flex-shrink: 0;
		}

		.biao_04 textarea {
			height: 80px;
			width: 90%;
			padding: 0 15px 0 10px;
			box-sizing: border-box;
			background: #FCFAED;
		}

		.biao_05 {
			padding: 15px 10px;
			border-bottom: 1px solid #EDEDED;
			display: flex;
		}

		.biao_05_1 {
			padding-top: 7px;
			flex-shrink: 0;
		}

		.biao_05_3 {
			padding: 7px 10px 0;
		}
		.time{display: flex;flex-grow: 1;font-size: 17px;}
		.mess_03 {
			display: flex;
			justify-content: space-between;
			padding: 20px 10px;
			border-bottom: 1px solid #F2F2F2;
			line-height: 20px;
		}

		.p_btn {
			background: #fff;
			padding: 0 10px;
			position: fixed;
			bottom: 0;
			width: 100%;
			z-index: 99;
		}

		.result {
			margin-top: 12upx;
			font-size: 28upx;
		}
	}
</style>